import "../../../../scss/activity/collect/come_on.scss";
import $ from "jquery";
import "../../../utils/weui";
import moment from "moment";
import Vue from "vue";
import com from "../../../utils/common";
import ReadSection from "../../components/readSection";
import FuncBanner from "../../components/funcbanner";
import CtrlPlay from "../../components/ctrlplay";
import UserJoin from "../../components/userJoin";
import ps from "../../../common/variable";
import wxtool from "../../components/weixin";
import count from "../../../utils/countdown";
import SharePop from "../../components/sharePop";
import viewAddFooter from "../../components/viewAddFooter";
import baseStatus from "../../components/baseActStatus";
import "../../../utils/oldcommon/layer"
import setWxShare from "../../components/setWxShare"
import Scroll from "../../../utils/rankSrcoll";
import NoticePop from "../../components/noticeWay";

let user = wxtool.getWxUserinfo();
console.log(user)
$(function () {
  let page = {
    _actid: com.getUrlParam("actid") ? com.getUrlParam("actid") : 1,
    _joinid: com.getUrlParam("joinid") ? com.getUrlParam("joinid") : 1,
    _ispreview: com.getUrlParam("preview") ? com.getUrlParam("preview") : 0,
    _appdata: {
      partinstatusall: ps, // 所有状态
      partinstatus: ps.ParterLook, //当前状态
      countDown: {
        days: "xx",
        hours: "xx",
        minutes: "xx",
        seconds: "xx"
      },
      JoinerMsg: {
        // 已报名用户信息
        Name: "信息",
        RankMsg: 3,
        NowTickets: 1
      },
      RankMsg: []
    },
    _app: {},
    _init: function () {
      let self = this;
      console.log(self._appdata)

      // 获取活动数据
      com.ajax({
        url: "/act/comeon/getActDetial",
        data: {
          Actid: self._actid,
          Joinid: self._joinid,
          Openid: user.openid,
        },
        ok: function (data) {
          let temp = data["msg"];
          console.log(data);
          if (temp !== "fail" && typeof temp === "object") {
            if(temp.Catgory == "collect/come_on") {
              console.log(temp);
              temp.Actid = self._actid;
              temp.Other = JSON.parse(temp.Other);
              temp.StartDate = moment(temp.StartTime).format("YYYY-MM-DD HH:mm");
              temp.EndDate = moment(temp.EndTime).format("YYYY-MM-DD HH:mm");
              temp.Content = JSON.parse(temp.Content);

              $("#PageTitle").html(temp.Title)
              // 分享相关信息
              let ShareMsg = {};
              ShareMsg.ShareImg = temp.ShareImg;
              ShareMsg.ShareTitle = temp.ShareTitle ? temp.ShareTitle : temp.Title;
              ShareMsg.ShareContent = temp.ShareContent;
              self._appdata.ShareMsg = ShareMsg;

              if (self._joinid > 1) {
                let JoinerMsg = {};
                JoinerMsg.NowTickets = parseInt(data["extra"].Current);
                JoinerMsg.Name = data["extra"].Name;
                JoinerMsg.RankMsg = data["joinRank"];
                self._appdata.JoinerMsg = JoinerMsg;
              }
              // 判断状态
              self._appdata.partinstatus = baseStatus(data);
              let ActStatus = {};
              ActStatus.partinstatusall = ps;
              ActStatus.partinstatus = self._appdata.partinstatus;
              self._appdata.ActStatus = ActStatus;
              $.extend(self._appdata, temp);
              page._loadTemp(data);
            }else{
              com.alertDialog("活动类型错误")
            }
          } else {
            com.alertDialog("活动不存在")
          }
        }
      });
    },
    _analysisData: function (data) {
      for (let i = 0; i < data.length; i++) {
        page._appdata.RankMsg.push({
          "Name": data[i].Name,
          "Ticket": data[i].Current.toFixed(0)
        })
      }
    },

    // 根据状态判断数据传输,页面交互
    _analysisStatus: function () {
      let self = this;
      if(self._ispreview){
        $(".preview-footer a:first-child").attr("href", "/dist/activity/collect/come_on_edit.html?actid=" + self._actid)
        $(".preview-footer a:last-child").attr("href", "/dist/activity/collect/come_on.html?actid=" + self._actid)
      }
      // 用户信息(当打开的是已经有用户报名的链接时)(当是用户打开时)
      if (self._joinid > 1) {
        // 检测是否帮忙已经帮忙(是否已经在伙伴里面)
        // 每次用户打开链接都填充分享内容
        let shareData = {
          ShareImg: self._appdata.ShareMsg.ShareImg,
          ShareContent: self._appdata.ShareMsg.ShareContent,
          Actid: self._actid,
        }
        let shareTitle = self._appdata.ShareMsg.ShareTitle;
        let joinerMsg = self._appdata.JoinerMsg;
        console.log(joinerMsg)
        shareData.ShareTitle = joinerMsg.Name + "正在参加" + shareTitle;
        setWxShare.SetShare(shareData)
      }
      else {

        if(!self._ispreview) {
          // 没有人报名时的情况(大概率商家页)
          // 当是商家保存完活动打开页面后
          let checkEditUser = com.getdb(self._actid);
          if (checkEditUser) {
            $(".share_mask").show();
            com.showCenter($(".share_pop"));
            com.savedb(self._actid, false)
          }
          let shareData = {
            ShareTitle: self._appdata.ShareMsg.ShareTitle,
            ShareImg: self._appdata.ShareMsg.ShareImg,
            ShareContent: self._appdata.ShareMsg.ShareContent,
            Actid: self._actid,
          }
          setWxShare.SetShare(shareData)
        }
      }
      // 当不是本人时设置出现砍价请求
      if (self._joinid > 1 && self._appdata.partinstatus != self._appdata.partinstatusall.JoinDone) {
        self._takePartInComeon()
      }
      // 跳出报名成功弹窗(此时标识用户在自己页面)
      if (self._appdata.partinstatus == self._appdata.partinstatusall.JoinDone) {
        let saveKey = user.openid + self._actid;
        let pageActId = com.getdb(saveKey);
        // 当当前用户第一次打开页面时(此时没有存储活动id)
        if (pageActId != self._actid) {
          com.savedb(saveKey, self._actid);
          $('.notice_msg').show()
          com.showCenter($('.sign-suc'));
          // 点击页面自动刷新
          $("#app").on("click", ".sign-suc-footer,.mask", function () {
            $(".mask,.notice_msg,.sign-suc").hide();
            self._takePartInComeon()
          });
        }
      }
    },
    _getJoinByOpenid: function (status) {
      let self = this;
      com.ajax({
        url: "/act/comeon/getJoinUserDetail",
        data: {
          Openid: user.openid,
          Actid: self._actid,
        },
        ok: function (dat) {
          console.log(dat);
          let joinMsg = dat["res"];
          console.log(joinMsg);
          if (joinMsg["Id"] > 0) {
            if (status) {
              window.location = "/dist/activity/collect/come_on.html?actid=" + self._actid + "&joinid=" + joinMsg["Id"];
            }
          } else {
            com.alertDialog("您还未参加活动");
          }

        }
      })
    },
    _takePartInComeon: function () {
      let self = this;
      com.ajax({
        url: "/act/comeon/takePartinComeOn",
        data: {
          Openid: user.openid,
          Actid: self._actid,
          Joinid: self._joinid,
          Catgory: "collect/come_on",
        },
        ok: function (data) {
          if (data["msg"] == "ok") {
            self._appdata.JoinerMsg.NowTickets++;
            $(".refueling_suc_notify , .come-mask").show();
            let Rocket = document.getElementById("start_rocket"); // 获取动画
            setTimeout(function () {
              // 动画结束时回调
              $(".mask").click(function () {
                $(".refueling_suc_notify , .come-mask").hide();
              });
            }, 3000);
          } else {
            com.alertDialog("您已经帮他加过油了");
          }
        }
      })
    },
    _loadTemp: function (data) {
      let self = this;
      Vue.component("g-section", ReadSection);
      Vue.component("func-banner", FuncBanner);
      Vue.component("music", CtrlPlay);
      Vue.component("user-join", UserJoin);
      Vue.component("share-pop", SharePop);
      Vue.component("add-msg", viewAddFooter);
      Vue.component("notice-pop", NoticePop);
      console.log(self._appdata)
      self._app = new Vue({
        el: "#app",
        data: self._appdata,
        methods: {
          getReadSection: function (val) {
            console.log(val)
            this.Section = val["Section"];
          },
          AlertJoinPop: function () {
            let msg = '<p style="text-align:left;color:#333;">①报名前可先联系商家，确认活动真实性以及记录联系方式哦！<br/>②如发现虚假活动，请在客牛公众号回复我们。</p>';
            layer.open({
              content: msg
              , btn: ['确定', '取消'],
              yes: function () {
                layer.closeAll();
                $('.pop_mask').show();
                com.showCenter($(".pop_user_msg"))
              }
            });
          },
          SendFriend: function () {
            $(".notice_msg").show()
            com.showCenter($('.sign-suc'))
          },
          // 提交报名信息
          UserJoinAct: function (data) {
            let JoinData = {};
            JoinData.Actid = self._actid;
            JoinData.Joinid = self._joinid;
            JoinData.ActivityCat = "collect/come_on";
            JoinData.Name = data["Name"];
            JoinData.Mobile = data["Mobile"];
            JoinData.Other = data["Other"];
            JoinData.Openid = user.openid;
            console.log(data);
            console.log(JoinData);
            com.ajax({
              url: "/act/comeon/joinComeOn",
              method: "post",
              data: JoinData,
              ok: function (data) {
                console.log(data);
                if (data["msg"] == "ok") {
                  self._getJoinByOpenid(1)
                }else{
                  com.alertDialog("不可重复参加")
                }
              }
            })
          },

          // 返回自己页面
          BackMine: function () {
            self._getJoinByOpenid(1)
          },
          TakePartIn: function () {
            self._takePartInComeon();
          },
        },
        updated: function () {
        }
      })
      self._analysisStatus();
      self._afterTemp()
    },
    _afterTemp: function () {
      let self = this;
      // 当是商家保存完活动打开页面后

      $("#app").on("click", ".mask,.cancel,.pop_mask,.close", function () {
        $(".mask,.pop_mask").hide();
      })
      $("#app").on("click", ".share_pop,.pop_user_msg,.share-way,.sign-suc", function (event) {
        event.stopPropagation();
      })

      // 倒计时
      let countDownTime = setInterval(function () {
        let timeRecord = count.computedTime(moment(self._app.EndDate).format("X"));
        if (timeRecord) {
          self._app.countDown = timeRecord;
        } else {
          self._app.partinstatus = self._app.partinstatusall.AtActInActiveEnd;
          clearInterval(countDownTime)
        }
      }, 1000);

      let obj = {
        url: "/act/comeon/getSortList",
        data: {
          PageNum: 5,
          Actid: page._actid,
        },
        callback: self._analysisData
      }
      Scroll.StartScroll(obj)
    },
  }
  page._init();
});

